#!/bin/bash

# 修复后端目录位置问题的脚本
echo "======================================"
echo "    查找并修复后端服务"
echo "======================================"

# 查找可能的后端目录
echo "正在查找后端目录..."
POSSIBLE_DIRS=(
    "/opt/cumbull/backend"
    "/root/backend"
    "/home/backend"
    "/var/www/backend"
    "/opt/backend"
    "/usr/local/backend"
    "$(find /root -name "start-server.js" -type f 2>/dev/null | head -1 | xargs dirname)"
    "$(find /opt -name "start-server.js" -type f 2>/dev/null | head -1 | xargs dirname)"
    "$(find /home -name "start-server.js" -type f 2>/dev/null | head -1 | xargs dirname)"
)

BACKEND_DIR=""
for dir in "${POSSIBLE_DIRS[@]}"; do
    if [ -n "$dir" ] && [ -d "$dir" ] && [ -f "$dir/start-server.js" ]; then
        BACKEND_DIR="$dir"
        echo "✓ 找到后端目录: $BACKEND_DIR"
        break
    fi
done

if [ -z "$BACKEND_DIR" ]; then
    echo "❌ 未找到后端目录，尝试查找所有Node.js文件..."
    echo "查找结果:"
    find / -name "*.js" -path "*/backend/*" 2>/dev/null | head -10
    echo
    find / -name "start-server.js" 2>/dev/null
    echo
    find / -name "app.js" -path "*/backend/*" 2>/dev/null
    echo
    echo "请手动指定后端目录位置"
    exit 1
fi

echo "使用后端目录: $BACKEND_DIR"
cd "$BACKEND_DIR"

# 检查必要文件
echo "检查必要文件..."
ls -la
echo

# 配置环境变量
echo "配置环境变量..."
cat > .env.production << 'EOF'
PORT=8080
NODE_ENV=production
DB_HOST=localhost
DB_USER=cumbull_user
DB_PASSWORD=CuMrBull2024!
DB_NAME=cumbull_db
JWT_SECRET=your-super-secret-jwt-key-2024
CORS_ORIGIN=*
EOF

echo "✓ 环境变量已配置"
cat .env.production
echo

# 检查Node.js版本
echo "Node.js版本: $(node --version)"
echo "npm版本: $(npm --version)"
echo

# 检查依赖
if [ -f "package.json" ]; then
    echo "检查依赖..."
    if [ ! -d "node_modules" ]; then
        echo "安装依赖..."
        npm install --production
    fi
fi

# 启动服务
echo "启动Node.js服务..."
mkdir -p /var/log
nohup node start-server.js > /var/log/backend.log 2>&1 &
SERVICE_PID=$!
echo "服务已启动，PID: $SERVICE_PID"

# 等待启动
echo "等待服务启动..."
sleep 5

# 检查进程状态
echo "检查进程状态..."
ps aux | grep node | grep -v grep
echo

# 检查端口
echo "检查端口监听..."
netstat -tlnp | grep 8080
echo

# 检查日志
echo "检查服务日志..."
if [ -f "/var/log/backend.log" ]; then
    echo "=== 服务日志 ==="
    tail -20 /var/log/backend.log
else
    echo "日志文件不存在"
fi
echo

# 测试连接
echo "测试本地连接..."
curl -s -m 5 http://localhost:8080/health || echo "健康检查失败"
echo
curl -s -m 5 http://localhost:8080/api || echo "API测试失败"
echo

echo "======================================"
echo "修复完成！"
echo "后端目录: $BACKEND_DIR"
echo "外部访问: http://47.237.10.129:8080/health"
echo "======================================"